import { ReportForms } from '@/api/interface/reportForms';

/**
 * @name: 饼图
 * @return {*}
 */
export const usePie = (api: Function, obj?: any, field?: string) => {
  console.log(field, 'field');

  let pieOption = reactive<any>({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      left: '0',
      orient: 'vertical'
    },
    title: {
      left: 'center',
      top: '30',
      textStyle: {
        color: '#000',
        fontSize: 16
      }
    },
    series: {
      name: '',
      type: 'pie',
      radius: '50%',
      label: {
        formatter: (params: any) => {
          const { data } = params || {};
          const { along, name } = data || {};
          return along ? name + ' | ' + along : name;
        }
      },
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  });
  let loading = ref(true);
  const getData = (params: any) => {
    api(params)
      .then((data: ReportForms.ResPdItemDwRiveIn_sumByDateScopeGpAll[]) => {
        pieOption.series.data = [];
        const f = (field || 'materialInfo,netWeight').split(',');

        data.forEach((item: any) => {
          pieOption.series.data.push({
            name: item[f[0]],
            along: f[1] === 'along' ? setHour(item[f[1]]) : item[f[1]],
            value: item[f[1]]
          });
        });
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });
  };

  onBeforeMount(() => {
    if (obj?.params) {
      Object.keys(obj.params).forEach(key => {
        if (!pieOption[key]) {
          pieOption[key] = obj.params[key];
        } else {
          Object.assign(pieOption[key], obj.params[key]);
        }
      });
    }
  });

  return {
    pieOption,
    loading,
    getData
  };
};
